<template>
	<div class="grid gap-2" :class="gridColsClass">
		<betting-option
			v-for="item in showSelections"
			:key="item.id"
			:selection="item"
			:match="match"
			:market="market"
			:animated="animated"
			:style="item.style" />
	</div>
</template>

<script lang="ts" setup>
import { PropType, computed } from 'vue'
import { Match, Market } from '@/types'
import BettingOption from '../betting-option/index.vue'
import { BettingTypeCode } from '@/enums'

const props = defineProps({
	match: {
		type: Object as PropType<Match>,
		required: true
	},
	market: {
		type: Object as PropType<Market>,
		required: true
	},
	animated: {
		type: Boolean,
		default: false
	}
})

const sides = computed(() => {
	const res: number[] = []
	props.market?.selections?.forEach(({ side }) => {
		if (res.length > 2) {
			return
		}
		if (!res.includes(side)) {
			res.push(side)
		}
	})
	return res
})

const gridColsClass = computed(() => {
	if (sides.value.length === 3) {
		return 'grid-cols-3'
	} else if (sides.value.length === 2) {
		return 'grid-cols-2'
	}
	if (props.market.selections?.length > 3) {
		return 'grid-cols-3'
	} else if (props.market.selections?.length > 2) {
		return 'grid-cols-2'
	}
	return 'grid-cols-1'
})

const showSelections = computed(() => {
	if (sides.value.length >= 2) {
		const res: any[] = []
		const posMap: any = {
			1: [],
			2: [],
			3: []
		}
		props.market?.selections.forEach((item) => {
			const { side } = item
			posMap[side].push(item)
		})
		if (
			props.market?.marketId?.substring(1, 3) === BettingTypeCode.handicap &&
			posMap[1]?.length &&
			'points' in posMap[1][0]
		) {
			posMap[1].sort((a: any, b: any) => a.points - b.points)
			if (sides.value.length > 2) {
				posMap[2].sort((a: any, b: any) => a.points - b.points)
				posMap[3].sort((a: any, b: any) => b.points - a.points)
			} else {
				posMap[3].sort((a: any, b: any) => b.points - a.points)
			}
		}
		Object.entries(posMap).forEach(([side, list]) => {
			;(list as any).forEach((item: any, index: number) => {
				const newItem = { ...item }
				let columnStart = +side
				if (gridColsClass.value === 'grid-cols-2' && columnStart === 3) {
					columnStart -= 1
				}
				const style: any = {}
				style['grid-column-start'] = columnStart
				style['grid-column-end'] = columnStart + 1
				style['grid-row-start'] = index + 1
				style['grid-row-end'] = index + 2
				newItem.style = style
				res.push(newItem)
			})
		})

		return res
	}
	return props.market.selections
})
</script>
